﻿#region Licence
// <copyright file="Core/NetworkStatus.cs" company="Kopigi">
// Copyright © Kopigi 2014
// </copyright>
// ****************************************************************************
// <author>Marc PLESSIS</author>
// <date>11/10/2014</date>
// <project>Nentang.wpf</project>
// <web>http://nentang.codeplex.com</web>
// <license>
// The MIT License (MIT)
// 
// Copyright (c) 2013 Marc Plessis
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// 
// </license>
#endregion
#region using

using System;
using System.Net.NetworkInformation;
using System.Runtime.CompilerServices;

#endregion

namespace Core.Class
{
    /// <summary>
	/// Provides notification of status changes related to Internet-specific network
	/// adapters on this machine.  All other adpaters such as tunneling and loopbacks
	/// are ignored.  Only connected IP adapters are considered.
	/// </summary>
	/// <remarks>
	/// <i>Implementation Note:</i>
	/// <para>
	/// Since we'll likely invoke the IsAvailable property very frequently, that should
	/// be very efficient.  So we wire up handlers for both NetworkAvailabilityChanged
	/// and NetworkAddressChanged and capture the state in the local isAvailable variable. 
	/// </para>
	/// </remarks>

	public static class NetworkStatus
	{
		private static bool _isAvailable;
		private static NetworkStatusChangedHandler _handler;

		/// <summary>
		/// Initialize the class by detecting the start condition.
		/// </summary>

		static NetworkStatus ()
		{
			_isAvailable = IsNetworkAvailable();
		}

		/// <summary>
		/// This event is fired when the overall Internet connectivity changes.  All
		/// non-Internet adpaters are ignored.  If at least one valid Internet connection
		/// is "up" then we consider the Internet "available".
		/// </summary>

		public static event NetworkStatusChangedHandler AvailabilityChanged
		{
			[MethodImpl(MethodImplOptions.Synchronized)]
			add
			{
				if (_handler == null)
				{
					NetworkChange.NetworkAvailabilityChanged
						+= new NetworkAvailabilityChangedEventHandler(DoNetworkAvailabilityChanged);

					NetworkChange.NetworkAddressChanged
						+= new NetworkAddressChangedEventHandler(DoNetworkAddressChanged);
				}

				_handler = (NetworkStatusChangedHandler)Delegate.Combine(_handler, value);
			}

			[MethodImpl(MethodImplOptions.Synchronized)]
			remove
			{
				_handler = (NetworkStatusChangedHandler)Delegate.Remove(_handler, value);

				if (_handler == null)
				{
					NetworkChange.NetworkAvailabilityChanged
						-= new NetworkAvailabilityChangedEventHandler(DoNetworkAvailabilityChanged);

					NetworkChange.NetworkAddressChanged
						-= new NetworkAddressChangedEventHandler(DoNetworkAddressChanged);
				}
			}
		}


		/// <summary>
		/// Gets a Boolean value indicating the current state of Internet connectivity.
		/// </summary>

		public static bool IsAvailable
		{
			get { return _isAvailable; }
		}

		/// <summary>
		/// Evaluate the online network adapters to determine if at least one of them
		/// is capable of connecting to the Internet.
		/// </summary>
		/// <returns></returns>

		private static bool IsNetworkAvailable ()
		{
			// only recognizes changes related to Internet adapters
			if (NetworkInterface.GetIsNetworkAvailable())
			{
				// however, this will include all adapters
				NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
				foreach (NetworkInterface face in interfaces)
				{
					// filter so we see only Internet adapters
					if (face.OperationalStatus == OperationalStatus.Up)
					{
						if ((face.NetworkInterfaceType != NetworkInterfaceType.Tunnel) &&
							(face.NetworkInterfaceType != NetworkInterfaceType.Loopback))
						{
							IPv4InterfaceStatistics statistics = face.GetIPv4Statistics();

							// all testing seems to prove that once an interface comes online
							// it has already accrued statistics for both received and sent...

							if ((statistics.BytesReceived > 0) &&
								(statistics.BytesSent > 0))
							{
								return true;
							}
						}
					}
				}
			}

			return false;
		}


		private static void DoNetworkAddressChanged (object sender, EventArgs e)
		{
			SignalAvailabilityChange(sender);
		}


		private static void DoNetworkAvailabilityChanged (
			object sender, NetworkAvailabilityEventArgs e)
		{
			SignalAvailabilityChange(sender);
		}


		private static void SignalAvailabilityChange (object sender)
		{
			bool change = IsNetworkAvailable();

			if (change != _isAvailable)
			{
				_isAvailable = change;

				if (_handler != null)
				{
					_handler(sender, new NetworkStatusChangedArgs(_isAvailable));
				}
			}
		}
	}
}